package com.ljx.rbac.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.rbac.domain.dto.UserDto;
import com.ljx.rbac.domain.entity.User;
import com.ljx.rbac.domain.vo.LoginReq;
import com.ljx.rbac.domain.vo.LoginResp;
import com.ljx.rbac.exception.ApiException;
import com.ljx.rbac.mapper.UserMapper;
import com.ljx.rbac.service.PermissionService;
import com.ljx.rbac.service.UserService;
import com.ljx.rbac.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-01  19:48
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginResp login(LoginReq loginReq) {
        if (Objects.isNull(loginReq) || StrUtil.isEmpty(loginReq.getUsername()) || StrUtil.isEmpty(loginReq.getPassword())){
            throw new ApiException("参数不能为空");
        }

        User user = checkAndGetUser(loginReq);
        String token = UserUtil.createToken(user.getId());
        UserDto userDto = saveUserCache(user);

        return LoginResp.builder()
                .token(token)
                .userInfo(userDto)
                .build();
    }

    private UserDto saveUserCache(User user) {
        UserDto userDto = BeanUtil.copyProperties(user, UserDto.class);
        userDto.setPermissions(UserUtil.tryToGetUserPermission(user.getId()));
        userDto.setRoles(UserUtil.tryToGetUserRole(user.getId()));
        userDto.setMenus(UserUtil.tryToGetUserMenu(user.getId()));
        UserUtil.setUserCache(userDto);

        return userDto;
    }

    private User checkAndGetUser(LoginReq loginReq) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginReq.getUsername()));
        boolean flag = Objects.isNull(user) || !user.getPassword().equals(DigestUtils.md5DigestAsHex(loginReq.getPassword().getBytes()));
        if (flag){
            throw new ApiException("用户名或者密码错误");
        }

        return user;
    }

    @Override
    public User register(LoginReq loginReq) {
        User user = new User(loginReq.getUsername(), loginReq.getPassword());
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.insert(user);
        return user;
    }
}
